package org.proxywars.engine.rts.units;

import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;

import org.proxywars.engine.rts.ICommand;
import org.proxywars.engine.rts.IEquipment;
import org.proxywars.engine.rts.IEvent;
import org.proxywars.engine.rts.IParty;
import org.proxywars.engine.rts.IUnit;
import org.proxywars.engine.rts.IUnitGroup;
import org.proxywars.engine.rts.attributes.Attributed;
import org.proxywars.engine.rts.events.TimerEvent;

public abstract class AbstractUnit extends Attributed implements IUnit {

	private Queue<ICommand> commands = new PriorityQueue<ICommand>();
	private List<IEquipment> equipment = new ArrayList<IEquipment>();
	private ICommand currentCommand;
	private IParty owner;
	private IUnit target;

	public AbstractUnit(IParty owner) {
		this.owner = owner;
	}

	@Override
	public void addCommand(ICommand command) {
		command.setOwner(owner);
		commands.add(command);
	}

	@Override
	public void addEquipment(IEquipment equipment) {
		this.equipment.add(equipment);
	}

	@Override
	public ICommand getCurrentCommand() {
		return currentCommand;
	}
	
	@Override
	public Queue<ICommand> getCommands() {
		return commands;
	}

	@Override
	public List<IEquipment> getEquipment() {
		return equipment;
	}

	@Override
	public IParty getOwner() {
		return owner;
	}

	@Override
	public IUnit getTarget() {
		return target;
	}

	@Override
	public void joinGroup(IUnitGroup group) {
	}

	@Override
	public void leaveGroup(IUnitGroup group) {
	}

	@Override
	public void setOwner(IParty owner) {
		this.owner = owner;
	}

	@Override
	public void setTarget(IUnit target) {
		this.target = target;
	}

	@Override
	public void handleEvent(IEvent event) {
		if (event instanceof TimerEvent) {
			processCommand();
		}
	}

	private void processCommand() {
		if (currentCommand == null)
			currentCommand = commands.poll();

		if (currentCommand != null) {
			if (!currentCommand.isCanceled()) {
				currentCommand.process();
				if (currentCommand.getCompletion() >= 1.0)
					currentCommand = null;
			} else
				currentCommand = null;
		}
	}
}
